package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

    @Component
    public class SpringSecurityUserService implements UserDetailsService {

        @Reference
        private UserService userService;
        @Autowired
        private PasswordEncoder passwordEncoder;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        User user = userService.findByUsername(username);
        if (user ==null) {
            return null;
        }

        // 获取用户密码
        String password = user.getPassword();
        // 创建集合，存放权限信息
        List<GrantedAuthority> list = new ArrayList<>();

        // 获取用户具有的角色
        Set<Role> roles = user.getRoles();
        // 遍历角色获取权限
        for (Role role : roles) {
            // 添加角色
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            // 遍历权限
            for (Permission permission : permissions) {
                // 添加权限
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        org.springframework.security.core.userdetails.User s_user = new org.springframework.security.core.userdetails.User
                (username,password,list);

        System.out.println(password);
        System.out.println(new BCryptPasswordEncoder().matches("admin",password));

        return s_user;
    }
}
